<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "user_history".
 *
 * @property int $id
 * @property int $user_id 用户id
 * @property int $good_id 商品id
 * @property int $created_at 创建时间
 */
class UserHistory extends Base
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'user_history';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['user_id', 'good_id', 'created_at'], 'integer'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'user_id' => 'User ID',
            'good_id' => 'Good ID',
            'created_at' => 'Created At',
        ];
    }

    public static function saveRecord($good_id, $user_id) {
      $user_history = UserHistory::find()->where(['user_id' => $user_id, 'good_id' => $good_id])->one();
      if (!$user_history) {
        $user_history = new UserHistory();
        $user_history->user_id = $user_id;
        $user_history->good_id = $good_id;
      }
      $user_history->created_at = time();
      $user_history->save();
    }

    public function getGood(){
      return $this->hasOne(Good::class, ['id' => 'good_id']);
    }
}
